#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      patrick
#
# Created:     16/05/2012
# Copyright:   (c) patrick 2012
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python


from moddt8837 import *
import pylab as plt
import time
import numpy as np
import scipy as sc
import struct

DEV1 = "TCPIP::169.254.241.13::INSTR";
DEV2 ='TCPIP::169.254.241.19::INSTR';

#-------------------------------------------------------------------------------
# reccupere le handle des boitiers
#-------------------------------------------------------------------------------
h1 = getHandle(DEV1)
h2 = getHandle(DEV2)

#-------------------------------------------------------------------------------
# lecture du nom des boitires, identification
#-------------------------------------------------------------------------------
s1=getID(h1)
s2=getID(h2)
print s1,' / ',s2

#-------------------------------------------------------------------------------
# reset des modules
#-------------------------------------------------------------------------------
print "Reset des modules..."
err1 = doRST(h1)
err2 = doRST(h2)

#-------------------------------------------------------------------------------
# Enable AD for all channel
#-------------------------------------------------------------------------------
err = h1.write(":AD:ENAB OFF;:AD:BUFF:SIZe?")
print "taille buffer acquisition = ", h1.read()
print "Activation des  modules AD..."
err1 = setAdEnableAll(h1)
err2 = setAdEnableAll(h2)

#-------------------------------------------------------------------------------
# couplage AC/DC pour tous les modules
#-------------------------------------------------------------------------------
print "Couplage  des  voies en AC ..."
err1 = setCouplage(h1,'AC')
err2 = setCouplage(h2,'AC')

#-------------------------------------------------------------------------------
# mode acquisition du buffer wrap/no wrap
#-------------------------------------------------------------------------------
print "Mode acquisition buffer wrap/no wrap ..."
err1 = setWrap(h1,"off")  #  pas de buffer circulaire
err1 = setWrap(h2,"off")

##h1.write(":AD:BUFF:SIZe 10000")
##h2.write(":AD:BUFF:SIZe 10000")
##h1.write(":AD:ENAB ON")
##h2.write(":AD:ENAB ON")

#-------------------------------------------------------------------------------
# initialisation des gains pour toutes les voies  1/10
#-------------------------------------------------------------------------------
print "Initialisation des gains ..."
level=1   # 1V en entree
err1 = setGain(h1,level)
err2 = setGain(h2,level)

#-------------------------------------------------------------------------------
# horloge interne
#-------------------------------------------------------------------------------
print "Initialisation horloge interne ..."
err1=setADClockInternal(h1)
err2=setADClockInternal(h2)

#-------------------------------------------------------------------------------
# frequence horloge interne
#-------------------------------------------------------------------------------
print "Initialisation frequence horloge interne ..."
fs=10000   # 10000 Hz
err1=setFreqClock(h1,fs)
err2=setFreqClock(h2,fs)
dt=1.0/fs    #periode echantillonnange
#-------------------------------------------------------------------------------
# trigger immediat / software
#-------------------------------------------------------------------------------
print "Initialisation trigger source immediat ..."
err1=setAdTrigSourceImm(h1)
#err2=setAdTrigSourceImm(h2)

##err=h1.write(":AD:ENAB ON, (@1);:AD:BUFF:SIZe?")
##err = h1.write(":AD:ENAB ON,(@1,2,3,4);:AD:BUFF:SIZe?") # active channel 1 ,2,3,4
##print h1.read()
##err = h1.write(":AD:ENAB OFF,(@4);:AD:BUFF:SIZe?") # active channel 1 ,2,3,4
##print h1.read()
##err = h1.write(":AD:ENAB OFF,(@3);:AD:BUFF:SIZe?") # active channel 1 ,2,3,4
##print h1.read()
##err = h1.write(":AD:ENAB OFF,(@2);:AD:BUFF:SIZe?") # active channel 1 ,2,3,4
##print h1.read()
##err = h1.write(":AD:ENAB OFF;:AD:BUFF:SIZe?")
##print h1.read()
##print "Initialisation frequence horloge interne ..."
##fs=44100  # 10000 Hz
##err1=setFreqClock(h1,fs)
##err2=setFreqClock(h2,fs)
##err = h1.write(":AD:ENAB ON,(@1,2,3,4);:AD:BUFF:SIZe:SCAns?") # active channel 1 ,2,3,4
##print h1.read()
##exit(0)


#-------------------------------------------------------------------------------
# pret a lancer la mesure
#-------------------------------------------------------------------------------
print "Armement des mesures, pret a lancer ..."
err1=setAdArm(h1)
#err2=setAdArm(h2)

#-------------------------------------------------------------------------------
# lance la mesure la mesure
#-------------------------------------------------------------------------------
print "lance la mesure ...."
err1=setAdInit(h1)
#err2=setAdInit(h2)

tacq=1 # temps acquisition 2s
print "attente ..."
buffersize=tacq/dt # nombre d echantillon pour tacq
print "nb. element : ", buffersize

N=1000

nbblock=int(buffersize/N-1)
print "nb. de blocs : ",nbblock
time.sleep(tacq)  #attente 2s

#-------------------------------------------------------------------------------
# arrete la mesure la mesure
#-------------------------------------------------------------------------------
err1=setAdStop(h1)
#err2=setAdStop(h2)


#-------------------------------------------------------------------------------
# on reccupere les donnees
#-------------------------------------------------------------------------------
mess=":AD:FETCH? 0,"+str(N-1)
print mess
err1=h1.write (mess)
#    err2=h2.write (":AD:FETCH? 0, 4092")
#data=h1.read_values(format=single + big_endian)
data=h1.read_raw()
sizeHeader,sizeBuffer,header,buf =  readHeader(data)
print sizeHeader,sizeBuffer,header
plt.figure(1)
plt.plot(buf,'.-')
fic = open("sinus.dat","wb")
fic.write(data)
fic.close()
plt.show()
exit(0)












#    data2=h2.read_values()
#data = np.array(data)
fic = open("data.dat","wb")
fic.write(data)
fic.close()
s=struct.unpack_from('2c',data)
sizeHeader=int(s[1])
print sizeHeader
fmt=str(sizeHeader)+"c"
s=struct.unpack_from(fmt,data[2:])
L=len(s)
print s,L
sizeBuffer=0
for i in range(L):
    print i,s[i],(L-i-1)
    sizeBuffer = pow(10,i)*int(s[L-i-1]) + sizeBuffer
print "taille buffer = ",sizeBuffer
sizeBuffer=sizeBuffer-12
fmt=">"+str(sizeBuffer/4)+"l"
print fmt
buf=s=struct.unpack_from(fmt,data[20:])
buf = np.array(buf)
print buf.shape
data=buf[1::4]
plt.figure(1)
plt.plot(data)
plt.show()
exit(0)
#-------------------------------------------------------------------------------
i=1
mess=":AD:FETCH? "+str(i*N) +","+str(N)
print mess
err1=h1.write (mess)
#    err2=h2.write (":AD:FETCH? 0, 4092")
#data=h1.read_values(format=single + big_endian)
data1=h1.read_raw()
#    data2=h2.read_values()
#data = np.array(data)
fic = open("data1.dat","wb")
fic.write(data1)
fic.close()
s=struct.unpack_from('2c',data1)
sizeHeader=int(s[1])
print sizeHeader
fmt=str(sizeHeader)+"c"
s=struct.unpack_from(fmt,data1[2:])
L=len(s)
print s,L
sizeBuffer=0
for i in range(L):
    print i,s[i],(L-i-1)
    sizeBuffer = pow(10,i)*int(s[L-i-1]) + sizeBuffer
print "taille buffer = ",sizeBuffer
sizeBuffer=sizeBuffer-12
fmt=">"+str(sizeBuffer/4)+"l"
print fmt
buf1=s=struct.unpack_from(fmt,data1[20:])
buf1 = np.array(buf1)
print buf1.shape
data1=buf1[1::4]
plt.figure(2)
plt.plot(data1)
plt.show()
#-------------------------------------------------------------------------------


exit(0)

i=1
mess=":AD:FETCH? "+str(i*N) +","+str(N)
print mess
err1=h1.write (mess)
#    err2=h2.write (":AD:FETCH? 0, 4092")
##data=h1.read_values(format=single + big_endian)
data=h1.read_raw()
#    data2=h2.read_values()
#data = np.array(data)
fic = open("data1.dat","wb")
fic.write(data)
fic.close()


exit(0)
print "data shape ",data.shape
data=data[5::4]        # premier buffer
#
for i in range(1,nbblock):
    mess=":AD:FETCH? "+str(i*N) +","+str(N)
    print mess
    err1=h1.write (mess)
    #    err2=h2.write (":AD:FETCH? 0, 4092")
    data1=h1.read_values(format=single + big_endian)
    #    data2=h2.read_values()
    data1 = np.array(data1)
    print "data1 shape ",data1.shape
    data1=data1[5::4]
    #
    data=np.concatenate(( data,data1), axis=0)



plt.figure(1)
plt.plot(data)
plt.show()

exit(0)
#

#
DT1.write("AD:ENABle?")
print "AD 1 enable : 0 disable , 1 : enable"
print DT1.read()
DT2.write("AD:ENABle?")
print "AD 2 enable : 0 disable , 1 : enable"
print DT2.read()
#
print "gain ?"
DT1.write("AD:GAIN?")
print DT1.read()
DT2.write("AD:GAIN?")
print DT2.read()
#
DT1.write("AD:ENABle?")
print DT1.read()
#
print "channels actives"
DT1.write(":AD:ENAB ON,(@1,2)") # active channel 1 et 2
DT1.write(":AD:ENAB 0,(@3,4)")  # desactive channel 3 et 4
DT1.write("AD:ENABle?")
print DT1.read()
#
DT1.write(":AD:ENAB ON,(@1,2,3,4)") # active channel 1 a 4
DT1.write("AD:ENABle?")
print DT1.read()
#
print "couplage"
DT1.write(":AD:COUP AC,(@1,2)")  # couplage AC
DT1.write(":AD:COUP DC,(@3,4)")  # couplage DC
#
DT1.write(":AD:COUP?")
print DT1.read()
# gain
print "gain"
DT1.write(":AD:GAIN 1,(@1,2)")
DT1.write(":AD:GAIN 10,(@3,4)")
DT1.write(":AD:GAIN?")
print DT1.read()
#clock
DT1.write(":AD:CLOC:FREQ?")
print "clock frequency 1"
print DT1.read()
DT1.write(":AD:CLOC:FREQ 10000")  #initialise la frequence echantillonnage
DT1.write(":AD:CLOC:FREQ?")
print "clock frequency 1"
print DT1.read()
DT2.write(":AD:CLOC:FREQ?")
print "clock frequency 2"
print DT2.read()
#mode acquisition
print "mode"
DT1.write(":AD:BUFF:MODE?")
print DT1.read()
#buffer size
DT1.write(":AD:BUFFer:SIZe?")
print "buffer 1 size"
print DT1.read()
DT1.write(":AD:ENAB OFF")
DT1.write(":AD:BUFF:SIZe 10000")
DT1.write(":AD:ENAB ON")
DT1.write(":AD:BUFFer:SIZe?")
print "buffer 1 size"
print DT1.read()
# trigger externe
print "trigger"
DT1.write(":AD:TRIG IMM")
##DT2.write(":AD:TRIG EXT")
DT1.write(":AD:TRIGger?")
print DT1.read()
# input buffer scan
print "buffer size"
DT1.write("AD:BUFFer:SIZe:SCAns?")
print DT1.read()
### max number of scan
##DT1.write("AD:FETCh?")
##print "max number of scan"
##print DT1.read()

# acquisition
DT1.write ("AD:STATus?")
print "status"
ret= int(DT1.read())
print "status = ",ret & 3

##DT1.write ("AD:ARM")
##print "status"
##ret= int(DT1.read())
##print "status = ",ret & 2
ret = DT1.write ("AD:STATus?")
ret= int(DT1.read())
print "status = ", ret & 3
#erreur queue
DT1.write (":SYST:ERR:COUNT?")
ret = DT1.read ()
print "erreur queue = ", ret
# clear CLS queue
DT1.write ("*CLS")
DT2.write ("*CLS")
#erreur queue
DT1.write (":SYST:ERR:COUNT?")
ret = DT1.read ()
print "erreur queue = ", ret
#erreur queue
DT2.write (":SYST:ERR:COUNT?")
ret = DT2.read ()
print "erreur queue = ", ret

#initialise et arme
print ":AD:ARM;:AD:INIT"
ret = DT1.write (":AD:ARM;:AD:INIT")
print "err = ",ret

time.sleep (1)
ret = DT1.write(":AD:ABORt")
print "err = ",ret

# status
ret = DT1.write (":AD:STAT?;:AD:STAT:SCAN?")
print "status  = ",ret

#fetch
ret = DT1.write (":AD:FETCH? 1, 10000")
print "fetch return"
print ret
ret = DT1.read ()
print ret, type(ret)
##plt.figure(1)
##signal = ret[1:-1]
##plt.plot(signal)
##plt.show()
##ret = DT1.write (":CURVe?")
##print ret
##ret = DT1.read ()
##print ret, type(ret)

####my_instrument_handle = vpp43.open(resource_manager.session, Dev1,
####VI_EXCLUSIVE_LOCK)
##my_instrument = instrument(Dev1, values_format = single)
##my_instrument.close()
##buf= my_instrument.read_raw()
##print type(buf)
##exit(0)

